package com.atguigu.spzx.cloud.order.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 对openfeign远程调用进行拦截。在调用者端发送请求的时候拦截。
 */
@Component
public class HeadersInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        System.out.println("HeadersInterceptor apply 帮Openfeign远程调用挂请求头");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        if(StringUtils.hasText(token)){
            System.out.println("HeadersInterceptor apply  token = "+token);
            template.header("token",token);
        }
    }
}
